package com.schoolcloud.serve.controller;

import com.schoolcloud.common.model.PageDTO;
import com.schoolcloud.common.model.R;
import com.schoolcloud.serve.dto.AttributeAndValuesDTO;
import com.schoolcloud.serve.entity.SkuAttribute;
import com.schoolcloud.serve.query.SkuAttributeQuery;
import com.schoolcloud.serve.service.SkuAttributeService;
import com.schoolcloud.serve.service.SkuInteractionService;
import com.schoolcloud.serve.vo.AttributeAssociatedVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/serve/re-market/sku/attribute")
@RequiredArgsConstructor
public class SkuAttributeController {
    private final SkuAttributeService skuAttributeService;
    private final SkuInteractionService skuInteractionService;

    @GetMapping("/page")
    public R<PageDTO<SkuAttribute>> getSkuAttributePage(SkuAttributeQuery query) {
        PageDTO<SkuAttribute> attributePageDTO = skuAttributeService.getSkuAttributePage(query);
        return R.ok(attributePageDTO);
    }

    @GetMapping("/page/by-group")
    public R<PageDTO<AttributeAssociatedVO>> getSkuAttributePageByGroup(SkuAttributeQuery query) {
        PageDTO<AttributeAssociatedVO> vo = skuInteractionService.getSkuAttributePageByGroup(query);
        return R.ok(vo);
    }

    @PostMapping
    public R createSkuAttribute(@RequestBody SkuAttribute skuAttribute) {
        skuAttributeService.save(skuAttribute);
        return R.ok();
    }

    @PutMapping
    public R updateSkuAttribute(@RequestBody SkuAttribute skuAttribute) {
        skuAttributeService.updateById(skuAttribute);
        return R.ok();
    }

    @DeleteMapping("/{id}")
    public R deleteSkuAttribute(@PathVariable Long id) {
        skuAttributeService.removeById(id);
        return R.ok();
    }

    @GetMapping("/{id}")
    public R<SkuAttribute> getSkuAttributeById(@PathVariable Long id) {
        SkuAttribute skuAttribute = skuAttributeService.getById(id);
        return R.ok(skuAttribute);
    }

    @GetMapping("/by/category/{categoryId}")
    public R<List<SkuAttribute>> getSkuAttributeByCategoryId(@PathVariable String categoryId) {
        List<SkuAttribute> skuAttribute = skuAttributeService.getSkuAttributeByCategoryId(categoryId);
        return R.ok(skuAttribute);
    }

    @GetMapping("/sale/by/category/{categoryId}")
    public R<List<AttributeAndValuesDTO>> getSaleSkuAttributeByCategoryId(@PathVariable String categoryId) {
        List<SkuAttribute> skuAttribute = skuAttributeService.getSaleSkuAttributeByCategoryId(categoryId);
        List<AttributeAndValuesDTO> collect = skuAttribute.stream().map(item -> {
            AttributeAndValuesDTO dto = new AttributeAndValuesDTO();
            BeanUtils.copyProperties(item, dto);
            return dto;
        }).collect(Collectors.toList());
        return R.ok(collect);
    }
}
